<template>
  <div class="teacherManagement-container">
    <a-card class="layout-card">
      <a-row align="middle" justify="space-between">
        <SearchGroup
          :label-option="labelOption"
          @handleSearch="loadData(1)"
          @handleReset="reset"
          :searchOption="filterOption"
        />
        <a-col>
          <a-button
            class="btn"
            v-if="route.meta?.buttonList?.includes('TeacherInfoAdd')"
            type="primary"
            @click="handlOpen()"
          >
            <plus-outlined /> 新建
          </a-button>
          <a-upload
            :showUploadList="showAcountUploadList"
            accept=".xlsx, .xls, .dbf"
            v-model:file-list="fileAcountList"
            name="file"
            v-if="route.meta?.buttonList?.includes('TeacherInfoImporOperate')"
            :customRequest="customAcountRequest"
          >
            <a-button class="btn" type="primary"> 导入教师 </a-button>
          </a-upload>
          <a-upload
            :showUploadList="showUploadList"
            accept=".xlsx, .xls, .dbf"
            v-model:file-list="fileList"
            name="file"
            v-if="
              addSubjectForm.operateAccountCheckFlag &&
              route.meta?.buttonList?.includes('TeacherCheckImport')
            "
            :customRequest="customRequest"
          >
            <a-button class="btn" type="primary"> 导入教师检查数据 </a-button>
          </a-upload>
        </a-col>
      </a-row>

      <a-table
        :scroll="{ x: 1450 }"
        bordered
        rowKey="account"
        class="tablstyle"
        size="middle"
        :pagination="false"
        :dataSource="list"
        :columns="columns"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex == 'index'">
            {{ (curPage - 1) * pageSize + (index + 1) }}
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <a-button
              type="link"
              v-if="route.meta?.buttonList?.includes('TeacherInfoEdit')"
              :disabled="record.accountType == 'ADMIN'"
              @click="handlOpen(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              :title="record.accountState == 'NORMAL' ? '确认禁用吗?' : '确认启用吗?'"
              v-if="route.meta?.buttonList?.includes('TeacherDisable')"
              @confirm="conclose(record)"
            >
              <a-button
                type="link"
                :disabled="record.accountType == 'ADMIN'"
                :danger="record.accountState == 'NORMAL'"
              >
                {{ record.accountState == 'NORMAL' ? '禁用' : '启用' }}
              </a-button>
            </a-popconfirm>
            <a-button
              type="link"
              danger
              v-if="route.meta?.buttonList?.includes('TeacherInfoDelete')"
              :disabled="record.accountType == 'ADMIN'"
              @click="handelDelete(record.account)"
            >
              删除
            </a-button>
            <a-button
              type="link"
              :disabled="record.accountType == 'ADMIN'"
              v-if="route.meta?.buttonList?.includes('TeacherUpdatePasword')"
              @click="handlSetPwd(record)"
            >
              修改密码
            </a-button>
          </template>
        </template>
      </a-table>
      <a-pagination
        class="pagination"
        :show-total="total => `共 ${total} 条`"
        :show-size-changer="false"
        show-quick-jumper
        v-model:current="curPage"
        v-model:pageSize="pageSize"
        :total="total"
      />
    </a-card>

    <a-modal
      class="loading"
      :visible="addModalVisible"
      width="25%"
      :title="titlePop"
      @cancel="handleClose"
      @ok="handleOk"
    >
      <a-form class="form" :model="formStore" :rules="rules" ref="addFrom">
        <a-form-item label="教师姓名" name="jsxm">
          <a-input v-model:value="formStore.jsxm" placeholder="请输入教师姓名" />
        </a-form-item>
        <a-form-item label="教师账号" name="account">
          <a-input
            v-model:value="formStore.account"
            :disabled="titlePop === '编辑教师账号'"
            placeholder="请输入教师账号"
          />
        </a-form-item>
        <a-form-item label="所属学院" name="xydm" v-if="userInfo.accountType !== 'XY'">
          <a-select
            allowClear
            v-model:value="formStore.xydm"
            :options="collegeList"
            placeholder="请选择学院"
            show-search
            :filter-option="selectFilterOption"
          >
            <template #suffixIcon>
              <caret-down-outlined class="ant-select-suffix" />
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="设置密码" v-if="!formStore.autoId" name="pwd">
          <a-input v-model:value="formStore.pwd" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="重复密码" name="pwdTwo" v-if="!formStore.autoId">
          <a-input v-model:value="formStore.pwdTwo" placeholder="请输入密码" />
        </a-form-item>
      </a-form>
    </a-modal>

    <undatePasword v-model:setModalVisible="setModalVisible" v-model:account="formManagAccount" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { useList } from '/@/hooks/web/useList'
import { delConfirm } from '/@/hooks/web/useCommonMessage'

import undatePasword from '/@/views/system-manage/account-allocation/undatePasword.vue'

import { isArray } from '/@/utils/is'
import { useMessage } from '/@/hooks/web/useMessage'
import { uploadApi } from '/@/api/sys/upload'
import { useRoute } from 'vue-router'
const route: any = useRoute()
const { createMessage } = useMessage()
import {
  deleteByIds,
  getTeacherCard,
  setPipeStatus,
  addTeacher,
} from '/@/api/system-manage/teacher-info'
import { getCollegeList } from '/@/api/organization/collegeManage'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import { useUserStoreWithOut } from '/@/store/modules/user'
const userStore = useUserStoreWithOut()
const addSubjectForm = computed(() => userStore.getSysConfig)
const userInfo = <any>computed(() => userStore.getUserInfo)
const fileList = ref()
const fileAcountList = ref()
const addModalVisible = ref(false)
const formStore = ref<any>({})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    fixed: true,
  },
  {
    title: '教师账号',
    dataIndex: 'account',
    key: 'account',
    align: 'center',
  },
  {
    title: '教师姓名',
    dataIndex: 'jsxm',
    key: 'jsxm',
    align: 'center',
  },
  {
    title: '账号状态',
    dataIndex: 'accountState',
    key: 'accountState',
    align: 'center',
    customRender: params => {
      if (!isArray(commonStatusList.value)) return '--'
      let arr = commonStatusList.value.filter(e => e.dictCode == params.value)
      if (arr.length) return arr[0].dictName
      return '--'
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 450,
    // customRender: (params) => {
    //   if (!params.value) return '';
    //   return params.value.join('/');
    // },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 300,
    fixed: 'right',
  },
])

const rules = {
  jsxm: [{ required: true, message: '教师姓名不能为空', trigger: 'blur' }],
  account: [{ required: true, message: '教师编号不能为空', trigger: 'blur' }],
  checkedList: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
  pwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  pwdTwo: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  xydm: [{ required: true, message: '学院不能为空', trigger: 'blur' }],
}

const labelOption = ref<any>([
  { name: '教师账号', key: 'account', inputWidth: 150, labelWidth: 70 },
  { name: '教师姓名', key: 'jsxm', inputWidth: 150, labelWidth: 70 },
])

// 列表数据
const { reset, loadData, filterOption, curPage, total, pageSize, list } = useList(getTeacherCard)

// 学院列表
const collegeList = ref<any>([])
const getCollegeOption = async () => {
  try {
    const { data } = await getCollegeList({
      pageNum: 0,
      pageSize: 9999,
    })
    data.forEach(ele => {
      ele.codeName = `${ele.xydm}(${ele.xymc})`
      ele.value = ele.xydm
      ele.label = ele.codeName
    })
    collegeList.value = data.sort((a, b) => a.xydm - b.xydm)
  } catch (error) {
    console.log(error)
  }
}

// 筛选学院列表选项
const selectFilterOption = (input: string, option: any) => {
  return option.codeName.includes(input)
}

if (userInfo.value.xydm == '0') {
  labelOption.value.push({
    name: '所属学院',
    key: 'xydm',
    type: 'Select',
    selectOption: collegeList,
    inputWidth: 180,
    labelWidth: 70,
    fieldNames: {
      labelOptions: 'codeName',
      valueOptions: 'xydm',
    },
  })
}

// 弹窗管理
const addFrom = ref()
const handleClose = () => {
  addFrom.value.resetFields()
  formStore.value = cloneDeep({})
  addModalVisible.value = false
}

const handleOk = async () => {
  await addFrom.value.validate()
  if (!formStore.value.autoId) {
    formStore.value.accountType = 'PYJS'
    formStore.value.accountState = 'NORMAL'
    if (formStore.value.pwd != formStore.value.pwdTwo) {
      return message.error('密码不一致')
    }
  }

  addTeacher(formStore.value).then(res => {
    if (res.code == 200) {
      message.success('操作成功')
      loadData()
      handleClose()
    } else {
      message.error(res.message)
    }
  })
}

const titlePop = ref('')
// 新增编辑
const handlOpen = async (record: any = {}) => {
  formStore.value = cloneDeep(record)
  titlePop.value = formStore.value.account ? '编辑教师账号' : '新增教师账号'
  addModalVisible.value = true
}

// 删除账号
const handelDelete = account => {
  delConfirm(deleteByIds, { account }, loadData)
}

// 账号修改密码
const setModalVisible = ref(false)
const formManagAccount = ref('')
const handlSetPwd = async record => {
  formManagAccount.value = record.account
  setModalVisible.value = true
}

// 修改状态
const conclose = async record => {
  try {
    let { code, message } = await setPipeStatus({
      account: record.account,
      operateState: record.accountState == 'BAN',
    })
    if (code == 200) {
      record.accountState = record.accountState == 'BAN' ? 'NORMAL' : 'BAN'
    } else {
      createMessage.error(message)
    }
  } catch (err) {
    console.log(err)
  }
}

const showUploadList = ref(true)
// 导入教师校验
const customRequest = async file => {
  const fileNames = file.file.name.split('.')
  const fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
  if (fileType != 'dbf' && fileType != 'xlsx' && fileType != 'xls') {
    createMessage.warning('只能上传.xlsx、.xls或.dbf类型的文件！')
    showUploadList.value = false
    return
  }
  const {
    data: { code, message },
  }: any = await uploadApi(`/importExport/jsAccountCheckImport`, file)
  if (code === 200) {
    createMessage.success('教师信息导入成功')
    loadData()
  } else {
    createMessage.error(message)
  }
  showUploadList.value = false
}

const showAcountUploadList = ref(false)
// 导入教师
const customAcountRequest = async file => {
  const fileNames = file.file.name.split('.')
  const fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
  if (fileType != 'dbf' && fileType != 'xlsx' && fileType != 'xls') {
    createMessage.warning('只能上传.xlsx、.xls或.dbf类型的文件！')
    showAcountUploadList.value = false
    return
  }
  const {
    data: { code, data },
  }: any = await uploadApi(`/importExport/jsAccountImport`, file)
  if (code === 200) {
    createMessage.success('教师信息导入成功')
    loadData()
  } else {
    createMessage.success(
      `导入完成：成功人数：${data?.successCount}人；导入失败人数：${data?.failCount}人;`
    )
  }
  showAcountUploadList.value = false
}

const commonStatusList = ref<any>([])
import { getDictionaryList } from '/@/views/teacher/home/index'
onMounted(async () => {
  getDictionaryList('state', commonStatusList)
  getCollegeOption()
})
</script>
<style lang="less" scoped>
.teacherManagement-container {
  // height: @c_height;
}

.layout-card {
  border-radius: 8px;
}

.tablstyle {
  padding: 15px 0;
}

.btn {
  margin-left: 20px;
}

.form {
  padding: 18px;
}
</style>
<style lang="less">
.teacher-info {
  .ant-pagination {
    margin-top: 20px;
  }
}
</style>
